
<template>
  <el-card class="userinfo-container">
    <!-- 面板屑导航 -->
    <el-breadcrumb separator="/" style="margin-bottom: 40px">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>个人中心</el-breadcrumb-item>
      <el-breadcrumb-item>基本资料</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 面板屑导航 -->
    <el-form
      :model="infoForm"
      :rules="infoRuels"
      ref="infoRef"
      label-width="100px"
    >
      <el-form-item label="登录名称">
        <el-input v-model="infoForm.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="infoForm.nickname"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="infoForm.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUserInfo">提交修改</el-button>
        <el-button @click="resetInfo">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { reqUpdateUserInfo } from '@/api/user'
import { mapState, mapActions } from 'vuex'
export default {
  name: '',
  data () {
    return {
      // 表单信息对象
      infoForm: {},
      // 验证规则对象
      infoRuels: {
        nickname: [
          {
            required: true,
            message: '昵称不能为空',
            trigger: ['blur']
          },
          {
            pattern: /^\S{1,10}$/,
            message: '昵称是1-10个非空字符',
            trigger: ['blur']
          }
        ],
        email: [
          {
            required: true,
            message: '邮箱不能为空',
            trigger: ['blur']
          },
          {
            pattern: /^([a-z0-9_.-]+)@([\da-z.-]+)\.([a-z.]{2,6})$/,
            message: '邮箱格式不正确',
            trigger: ['blur']
          }
        ]
      }
    }
  },
  async created () {
    // 获取用户信息
    await this.getUserInfo()
    this.infoForm = { ...this.userInfo }
    console.log(this.userInfo, 444)
  },
  computed: {
    ...mapState('user', ['userInfo'])
  },
  methods: {
    ...mapActions('user', ['getUserInfo']),
    resetInfo () {
      this.infoForm = { ...this.userInfo }
      this.$refs.infoRef.resetFields()
    },
    /* 更新用户 */
    updateUserInfo () {
      // 1. 预校验
      this.$refs.infoRef.validate(async boo => {
        if (!boo) return
        // 2. 发送请求
        const { data } = await reqUpdateUserInfo(this.infoForm)
        // 3. 提示
        if (data.code !== 0) return this.$message.error(data.message)
        this.$message.success(data.message)
        // 4. 重新渲染 将vuex中的数据重新获取 调用getUserInfo
        this.getUserInfo()
      })
    }
  }
}
</script>
<style lang='less'  scoped>
.userinfo-container {
  .el-form {
    width: 500px;
  }
}
</style>
